package com.mall.util.distributed.raft.lifecycle;

import com.mall.util.distributed.raft.config.RaftConfig;
import com.mall.util.distributed.raft.election.ElectionTask;
import com.mall.util.distributed.raft.heartbeat.HeaderBeatTask;
import com.mall.util.distributed.raft.node.Node;
import com.mall.util.distributed.raft.pool.RaftThreadPool;
import com.mall.util.distributed.raft.rpc.RaftServer;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

@Slf4j
public class LifecycleManager implements Lifecycle {
    @Autowired
    private RaftConfig raftConfig;

    @Autowired
    private RaftServer raftServer;

    @Autowired
    private HeaderBeatTask heartBeatTask;

    @Autowired
    private ElectionTask electionTask;

    @Override
    public void shutdown(Consumer<Boolean> consumer) {
        log.info("System do shutdown beagin");

        raftServer.stop();

        consumer.accept(Boolean.TRUE);

        log.info("System do shutdown end");
    }

    /* 如何避免重复启动 */
    @Override
    public void init(Consumer<Boolean> consumer) {
        log.info("System do init beagin");

        var node = Node.getINSTANCE();

        node.setSelfAddress(raftConfig.getAddress());
        node.setPeerAddress(raftConfig.getPeerAddress());

        /* 开启系统的各类定时任务 */
        RaftThreadPool.getScheduled().scheduleWithFixedDelay(heartBeatTask, 0, 500, TimeUnit.MILLISECONDS);
        RaftThreadPool.getScheduled().scheduleAtFixedRate(electionTask, 6000, 500, TimeUnit.MILLISECONDS);

        raftServer.start();

        consumer.accept(Boolean.TRUE);

        log.info("System do init end");
    }
}
